//
//  SMWebViewController.m
//  DiDi
//
//  Created by huangtie on 2017/3/31.
//  Copyright © 2017年 Sinmore. All rights reserved.
//

#import "SMWebViewController.h"

@interface SMWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) NSString *originUrl;

@end

@implementation SMWebViewController

- (instancetype)initWithUrl:(NSString *)url {
    
    return [self initWithUrl:url title:nil];
}

- (instancetype)initWithUrl:(NSString *)url title:(NSString *)title {
    
    self = [super init];
    
    if (self) {
        
        self.title = title;
        _originUrl = url;
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];

    [self setupNavItem];
    [self setupWebView];
    [self loadUrl:_originUrl];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Private methods
- (void)setupNavItem {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close:)];
}

- (void)setupWebView {
    
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _webView.dataDetectorTypes = UIDataDetectorTypeNone;
    _webView.delegate = self;
    [self.view addSubview:_webView];
    
    __weak typeof (self) weakSelf = self;
    _webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.webView reload];
    }];
}


- (void)loadUrl:(NSString *)url {
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [_webView loadRequest:urlRequest];
}

#pragma mark - Actions

- (void)close:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Overwrite functions

- (void)ts_backClick {
    
    if (_webView.canGoBack) {
        [_webView goBack];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    
    [_webView.scrollView.mj_header endRefreshing];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [_webView.scrollView.mj_header endRefreshing];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (!self.title.length) {
        self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
}

@end
